﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Dapper;
using DotnetSpider.DataFlow;
using DotnetSpider.DataFlow.Parser;
using DotnetSpider.DataFlow.Storage;
using DotnetSpider.Http;
using DotnetSpider.RequestSupplier;
using DotnetSpider.Scheduler.Component;
using DotnetSpider.Selector;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;

using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RabbitMQ.Client;
using Serilog;
using static DotnetSpider.Lawyee.Src.LawSpider;
using StringContent = DotnetSpider.Http.StringContent;

namespace DotnetSpider.Lawyee.Src
{
	public class s2DataParser : DataParser
	{
		/// <summary>
		/// 生成细分过滤请求
		/// </summary>
		/// <param name="context"></param> 
		/// <param name="dataItemResult">左边菜单json</param>
		/// <param name="pageId"></param>
		/// <param name="condition"></param>
		public static void s2DataParserCreateSubRquest(DataContext context, JObject dataItemResult, string pageId, JArray condition)
		{
			string str = string.Empty;
			try
			{
				context.Request.SetProperty("lastConditionText", JsonConvert.SerializeObject(condition));

				//获取左边菜单
				JArray jarrayList = (JArray)dataItemResult["s33,s39,s40"];

				foreach (JObject subConditionItem in jarrayList)
				{
					DispaterCondition(context, subConditionItem, condition, pageId);
				}
			}
			catch (Exception ex)
			{
				Log.Logger.Error(ex.Message + "!!!"+ ex.StackTrace + "s2DataParser:CreateSubRquest:" + str);
			}
		}

		/// <summary>
		/// 递归处理多条件过虑
		/// </summary>
		/// <param name="context"></param>
		/// <param name="data">获取左边菜单，s33,39,40</param>
		/// <param name="condition"></param>
		/// <param name="conditionList">s33,39,40 值</param>
		/// <param name="pageId"></param>
		/// <param name="index"></param>
		protected static void DispaterCondition(DataContext context, JObject data, JArray condition, string pageId)
		{
			string str = string.Empty;
			try
			{
				int subCount = int.Parse(data["count"].ToString());

				


				if (subCount < MaxRecord && subCount > 0)
				{
					JArray condition_ = (JArray)condition.DeepClone();

					JObject jobj = new JObject();
					//第一级小于最大值600
					jobj.Add(new JProperty("key", "s33"));

					jobj.Add(new JProperty("value", data["value"].ToString()));

					condition_.Add(jobj);

					//RedisHelpers.ListLeftPush("wenshu", JsonConvert.SerializeObject(condition_));

					ScrollPage(subCount, pageId, condition_, context);
				}
				else
				{
					if (data.Property("childGroupFieldList") != null && data["childGroupFieldList"].GetType() == typeof(JArray))
					{
						JArray jarray1 = (JArray)data["childGroupFieldList"];

						foreach (JObject subItem1 in jarray1)
						{

							if (fylist.Find(p => p.code == subItem1["value"].ToString()) != null && Convert.ToInt32(subItem1["count"]) > LawSpider.MaxRecord)
							{
								JArray condition_ = (JArray)condition.DeepClone();

								JObject jobj = new JObject();

								jobj.Add(new JProperty("key", "s2"));

								jobj.Add(new JProperty("value", fylist.Find(p => p.code == subItem1["value"].ToString()).name));

								condition_.Add(jobj);

								Request request = ConditionRequst(context, condition_);

								context.AddFollowRequests(request);

								if (subItem1.Property("childGroupFieldList") != null && subItem1["childGroupFieldList"].GetType() == typeof(JArray))
								{
									JArray jarray2 = (JArray)subItem1["childGroupFieldList"];
									foreach (JObject subItem2 in jarray2)
									{

										if (fylist.Find(p => p.code == subItem2["value"].ToString()) != null)
										{
											JArray condition2_ = (JArray)condition.DeepClone();

											JObject jobj2 = new JObject();

											jobj2.Add(new JProperty("key", "s2"));

											jobj2.Add(new JProperty("value", fylist.Find(p => p.code == subItem2["value"].ToString()).name));

											condition2_.Add(jobj2);

											Request request2 = ConditionRequst(context, condition2_);

											context.AddFollowRequests(request2);
										}
										else
										{
											JArray condition2_ = (JArray)condition.DeepClone();

											JObject jobj2 = new JObject();

											jobj2.Add(new JProperty("key", "s40"));

											jobj2.Add(new JProperty("value", subItem2["value"].ToString()));

											condition2_.Add(jobj2);

											Request request2 = ConditionRequst(context, condition2_);

											context.AddFollowRequests(request2);
										}

									}
								}

							}
							else
							{
								JArray condition_ = (JArray)condition.DeepClone();

								JObject jobj = new JObject();

								jobj.Add(new JProperty("key", "s39"));

								jobj.Add(new JProperty("value", subItem1["value"].ToString()));

								condition_.Add(jobj);

								Request request = ConditionRequst(context, condition_);

								context.AddFollowRequests(request);
							}

							
						}
					}

					

				}
			}
			catch (Exception ex)
			{
				Log.Logger.Error(ex.Message + "!!!"+ ex.StackTrace + "s2DataParser:DispaterCondition:");
			}

		}

		protected class GetFYs
		{
			public string value { get; set; }
			public int count { get; set; }
		}

		/// <summary>
		/// 进一步过虑生成请求
		/// </summary>
		/// <param name="context"></param>
		/// <param name="condition"></param>
		/// <returns></returns>
		public static Request ConditionRequst(DataContext context, JArray condition)
		{
			Request request = null;

			try
			{
				string conditionText = JsonConvert.SerializeObject(condition);

				string pageId = context.Request.GetProperty("pageId");

				request = CreateDocDataItemRequest(conditionText, "s2DataParser", pageId);

				foreach (KeyValuePair<string, string> property in context.Request.Properties)
				{
					request.SetProperty(property.Key, property.Value);
				}

				request.SetProperty("conditionText", conditionText);


			}
			catch (Exception ex)
			{
				Log.Logger.Error(ex.Message + "!!!"+ ex.StackTrace + "s2DataParser:ConditionRequst:");
			}

			return request;
		}




		public s2DataParser()
		{
			AddRequiredValidatorEx("s2DataParser");
		}

		protected override Task Parse(DataContext context)
		{
			try
			{
				//左边菜单json
				var result = CommonHelper.CommonParser(context);

				if (string.IsNullOrEmpty(result) || !result.StartsWith("{") || !result.EndsWith("}"))
				{
					CommonHelper.RetryRequest(context);
					return Task.CompletedTask;
				}
				else
				{
					JObject dataItemResult = JObject.Parse(result);
					FilterData(context, dataItemResult);
				}

			}
			catch (Exception ex)
			{
				CommonHelper.RetryRequest(context);
				Log.Logger.Error(ex.Message + "!!!"+ ex.StackTrace + "s2DataParser:Parse:");
			}

			return Task.CompletedTask;

		}
		protected static void FilterData(DataContext context, JObject dataItemResult)
		{
			try
			{
				//总数
				int count = 0;
				if (dataItemResult.Property("s42") != null && dataItemResult["s42"].GetType() == typeof(JArray))
				{
					JArray jobjTotal = (JArray)dataItemResult["s42"];

					if (jobjTotal.Count > 0)
					{
						foreach (JObject everyYearTotal in jobjTotal)
						{
							count += int.Parse(everyYearTotal["count"].ToString());
						}
					}
				}

				string pageId = context.Request.GetProperty("pageId");

				JArray condition = JArray.Parse(context.Request.GetProperty("conditionText"));

				if (condition.Count() != 2)
				{
					string aaa = condition.ToString();
				}

				Dictionary<string, string> properties = context.Request.Properties;

				if (count <= MaxRecord && count > 0)  //小于当前设定值, 无需进行过虑
				{
					//直接查询文书id
					ScrollPage(count, pageId, condition, context);

				}
				else
				{ //解析过虑条件
					s17DataParser.s17DataParserCreateSubRquest(context, dataItemResult, pageId, condition);
				}

			}
			catch (Exception ex)
			{
				Log.Logger.Error(ex.Message + "!!!"+ ex.StackTrace + "s2DataParser:FilterData:");
			}

		}


















	}




































}
